﻿using DataTransfer.SDK;
using DataTransfer.SDK.Models;
using MiniFox.Data;
using MiniFox.Platform.Applications.Auth;
using MiniFox.Utility;
using System.Data;
using DataSourceFactory = MiniFox.Platform.DataSourceFactory;

namespace DataTransfer.Core.Services
{
    /// <summary>
    /// 默认数据写入器，从数据库命令工厂生成
    /// </summary>
    public class DefaultDataWriter : DataWriter
    {
        DataSourceFactory _factory;
        IExcelImporter _importer;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="importer"></param>
        /// <param name="authStateManagement"></param>
        public DefaultDataWriter(IExcelImporter importer, IAuthStateManagement authStateManagement) : base(importer, authStateManagement)
        {
            _importer = importer;
        }
        /// <summary>
        /// 
        /// </summary>
        protected new IExcelImporter Importer
        {
            get
            {
                return _importer;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        protected DataSourceFactory DataSourceFactory
        {
            get
            {
                _factory ??= GetComponent<DataSourceFactory>(AuthStateManagement);
                return _factory;

            }
        }

        public override SummaryModel[] ExecuteWrite(object originalData)
        {
            if (originalData is not DataSet dataSet)
                return null;
            List<SummaryModel> list = [];
            foreach (XDataTable dataTable in dataSet.Tables)
            {
                list.Add(WriteTable(dataTable));
            }
            SummaryModel[] summaries = [.. list];
            return summaries;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dataTable"></param>
        /// <returns></returns>
        protected virtual SummaryModel WriteTable(XDataTable dataTable)
        {

            var sheet = Importer.Sheets.SingleOrDefault(s => s.SheetName == dataTable.TableName);
            var command = DataSourceFactory.GetDataCommand(sheet.OperateName);

            command.CommandExecuting += Command_CommandExecuting;
            command.CommandExecuted += Command_CommandExecuted;
            command.OnError += Command_OnError;
            var updatedRows = dataTable.GetUpdatedRows();
            int updatedRowCount = updatedRows.Count;
            var deletedRows = dataTable.GetDeletedRows();
            int deletedRowCount = deletedRows.Count;
            dataTable.AcceptAllChanges();
            var rowCount = command.ExecuteOperation(dataTable);
            return new SummaryModel
            {
                Name = dataTable.TableName,
                TotalCount = dataTable.Rows.Count,
                SuccessCount = rowCount,
                FailCount = dataTable.Rows.Count - rowCount,
                UpdatedRowCount = updatedRowCount,
                DeletedRowCount = deletedRowCount
            };
        }

        private void Command_CommandExecuted(object? sender, CommandEventArgs e)
        {
        }

        private void Command_CommandExecuting(object? sender, CommandEventArgs e)
        {
        }

        private void Command_OnError(object? sender, CommandErrorEventArgs e)
        {
            var content = new
            {
                ImporterName = Name,
                e.ConnectionString,
                e.CommandText,
                e.Parameters,
                e.Error.Message
            };
            WriteErrorLog(content.ToJsonString(), e.Error);
        }

    }
}
